import { Base64 } from 'js-base64';

function generateRandomString(length = 30) {
  const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

function cc_encode(str: string): string {
  if (str === undefined || str === '') return '';
  if (str === null) return '';
  const encoder = new TextEncoder();
  const uint8array = encoder.encode(str);
  const base64Str = Base64.fromUint8Array(uint8array);
  return generateRandomString() + base64Str;
}

function cc_decode(str: string): string | boolean {
  try {
    if (str == '0') return str;
    const decodedStr = Base64.decode(str.slice(30));
    let result;
    if (decodedStr.includes('*') || decodedStr.includes('-')) {
      result = decodedStr;
    } else if (!isNaN(parseInt(decodedStr))) {
      result = parseInt(decodedStr);
    } else {
      result = decodedStr;
    }
    return result;
  } catch (error) {
    return str;
  }
}

function decodeObject(obj) {
  return obj;
  try {
    for (const key in obj) {
      if (Array.isArray(obj[key])) {
        obj[key] = decodeObject(obj[key]);
      } else if (typeof obj[key] === 'object') {
        obj[key] = decodeObject(obj[key]);
      } else {
        let aseFile = cc_decode(obj[key]);
        const isGarbled = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\xFF]|[\u{E000}-\u{F8FF}]/u.test(
          typeof aseFile === 'string' ? aseFile : '',
        );
        if (isGarbled) {
          aseFile = obj[key];
        }
        obj[key] = aseFile;
      }
    }
    return obj;
  } catch (error) {
    console.error('error', error);
    return obj;
  }
}

function encodeObject(obj) {
  return obj;
  for (const key in obj) {
    if (Array.isArray(obj[key])) {
      obj[key] = encodeObject(obj[key]);
    } else if (typeof obj[key] === 'object') {
      obj[key] = encodeObject(obj[key]);
    } else {
      obj[key] = cc_encode(obj[key]);
    }
  }
  return obj;
}

// 导出 cc_encode 和 cc_decode 函数
export default {
  cc_encode,
  cc_decode,
  decodeObject,
  encodeObject,
};
